var datagridFault;
var datagridDtl;
var dialogFault;
var dialogFaultDtl;
var dialogDtl;
var dialogFaultPreview;
var fill_device_id;
var old_fault_date;
$(function () {
    fill_device_id=null;
    datagridFault = $("#list").datagrid({
        method: "post",
        url: getRootPath() + "/fault/getFaultList",
        fit: true,
        border: true,
        pageNumber: 1,
        pageSize: 20,
        pageList: [10, 20, 30, 50, 100],
        columns: [[
            {field:'ck',checkbox:true},
            {field: "fault_id", title: "故障ID", width: 60},
            {field: "workshop", title: "所属车间", width: 120},
            {field: "line_name", title: "线体名称", width: 120},
            {field: "device_name", title: "设备名称", width: 100},
            {field: "device_num", title: "设备编号", width: 120},
            {field: "fault_type", title: "故障类型", width: 120,
                formatter: function (value) {
                    switch (value) {
                        case 0:return "元器件（物料）问题";
                        case 1:return "结构设计问题";
                        case 2:return "软件问题";
                        case 3:return "装配工艺问题";
                        case 4:return "其他问题";
                        default:return "未知故障类型";
                    }
                }},
            {field: "fault_phenomenon", title: "故障现象", width: 140,
                formatter: function (value) {
                    if (value!=null)
                    { return "<span title='" + value + "'>" + value + "</span>";}
                    else
                    {return "";}
                }},
            {field: "analyse", title: "故障分析", width: 140,
                formatter: function (value) {
                    if (value!=null)
                    { return "<span title='" + value + "'>" + value + "</span>";}
                    else
                    {return "";}
                }},
            {field: "maintenance_measures", title: "维修措施", width: 140,
                formatter: function (value) {
                    if (value!=null)
                    { return "<span title='" + value + "'>" + value + "</span>";}
                    else
                    {return "";}
                }},
            {field: "maintenance_time", title: "维修时长", width: 60},
            {field: "maintenance_person", title: "维修人", width: 100},
            {field: "fault_date", title: "故障日期", width: 120},
            {field: "remark", title: "备注", width: 160,
                formatter: function (value) {
                if (value!=null)
                { return "<span title='" + value + "'>" + value + "</span>";}
                else
                {return "";}
                }
            },
            {field:"operation",title:"操作",width:250,
                formatter:function(value,row,index){
                var elementNode ="<span>";
                var btn = "<button style=\"\" onclick=\"queryDetails("+row.fault_id+")\" class=\"button-edit button-green\">故障配件</button>";
                var btn2 = "<button style=\"margin-left: 5px;\" onclick=\"edit("+index+")\" class=\"button-edit button-yellow\">修改</button>";
                var btn3 = "<button style=\"margin-left: 5px;\" onclick=\"remove("+row.fault_id+")\" class=\"button-delete button-red\">删除</button>";
                elementNode=elementNode+btn+btn2+btn3+"</span>";
                return elementNode;
            }
            },
        ]],
        onLoadSuccess: function (data) {
            $('.button-delete').linkbutton({});
            $('.button-edit').linkbutton({});
        },
        onDblClickRow: function (index, row) {
            fault_preview(row);
        },
        pagination: true,
        striped: true,
        singleSelect:true,
        //工具条
        toolbar: "#toolbar",
    });
    //初始化select
    $.getJSON(getRootPath() + "/fault/getLineList", function (json) {
        $('#line_id').combobox({
            data: json.rows, //获取到的json 数据
            valueField: "line_id",
            textField: "line_name"
        });
    });

    $("#fault_type").combobox('setValue',null);
    $("#workshop").combobox('setValue',null);
    IniDetails();
    bindganged();
});

// 记录查询
function queryRecord() {
    $("#list").datagrid('load', {
        fault_type:$("#fault_type").combobox('getValue'),
        maintenance_person:$("#maintenance_person").val(),
        device_name:$("#device_name").val(),
        device_num:$("#device_num").val(),
        workshop:$("#workshop").combobox('getValue'),
        line_id:$("#line_id").combobox('getValue'),
        start_fault_date:$("#start_fault_date").val(),
        end_fault_date:$("#end_fault_date").val(),
        }
    );
}
function IniDetails() {
    datagridDtl = $("#details_list").datagrid({
        method: "post",
        url: getRootPath() + "/fault/getUnitList",
        fit: true,
        border: true,
        pageNumber: 1,
        pageSize: 20,
        pageList: [10, 20, 30, 50, 100],
        columns: [[
            {field:'ck',checkbox:true},
            {field: "fault_unit_id", title: "uid", width: 30,hidden:true},
            {field: "type_dtl_name", title: "配件名", width: 100},
            {field: "type_dtl_no", title: "配件编号", width: 100},
            {field: "sizes", title: "配件规格", width: 100},
            {field: "unit_count", title: "数量", width: 80},
            {field:"operation",title:"操作",width:170,
                formatter:function(value,row,index){
                    var elementNode ="<span>";
                    var btn = "<button style=\"margin-left: 5px;\" onclick=\"editDtl("+index+")\" class=\"button-edit button-yellow\">修改</button>";
                    var btn1 = "<button style=\"margin-left: 5px;\" onclick=\"removeDtl("+row.fault_unit_id+")\" class=\"button-delete button-red\">删除</button>";
                    elementNode=elementNode+btn+btn1+"</span>";
                    return elementNode;
                }
            },
        ]],
        onLoadSuccess: function (data) {
            $('.button-delete').linkbutton({});
            $('.button-edit').linkbutton({});
        },
        pagination: true,
        striped: true,
        singleSelect:true,
        //工具条
        toolbar: "#details_list_toolbar",
        queryParams: {
            fault_id:1
        }
    });
}

function queryDetails(fault_id) {
    if (fault_id!=null)
    {
        $("#dlg_faultid").val(fault_id);
        console.info("queryDetails:fault_id="+$("#dlg_faultid").val());
        dialogFaultDtl = $("#dlg_details").dialog({
            title: '故障配件单元细则',
            width: 570,
            height: 400,
            maximizable: false,
            modal: true,
            buttons: [{
                text: '关闭',
                handler: function () {
                    dialogFaultDtl.dialog('close');
                }
            }]
        });
    }
    console.info("load:"+$("#dlg_faultid").val());
    $("#details_list").datagrid('load', {
        fault_id:$("#dlg_faultid").val()
        });
}

function remove(id) {
    if (id == null) {
        var row = datagridFault.datagrid('getSelected');
        if (row == null) {
            U.msg('请先选择故障事件');
            return;
        } else {
            id = row.fault_id;
        }
    }

    parent.$.messager.confirm('提示', '删除后该故障的故障配件单元数据也将会删除且无法恢复您确定要删除？', function (data) {
        if (data) {
            U.get({
                url: getRootPath() + '/fault/deleFault?fault_id=' + id,
                loading: true,
                success: function (data) {
                    if (data.code == 200) {
                        U.msg('删除成功');
                        queryRecord();
                    } else if (data.code == 400) {//参数验证失败
                        U.msg('参数验证失败');
                    } else if (data.code == 403) {
                        U.msg(data.message);
                    }
                    else {
                        U.msg('未知异常');
                    }
                }
            });
        }
    });
}

function add() {
    $('.Unit_Add_Option').css('display','');

    dialogFault = $("#dlg_fault").dialog({
        title: '添加故障事件',
        width: 520,
        height: 480,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '确认',
            iconCls: 'icon-ok',
            handler: function () {
                var isValid = $("#form_fault").form('validate');
                var rows = $('#form_unit_list_temp').datagrid('getRows');
                var jsonstr=JSON.stringify(rows);
                var addObj = [{"name":"unit_list","value":jsonstr}];
                if (isValid) {
                    U.post({
                        url: getRootPath() + "/fault/addFault",
                        loading: true,
                        data: getFormJson("#form_fault", "", addObj),//$('#form_main').serialize(),
                        success: function (data) {
                            if (data.code == 200) {
                                U.msg('添加成功');
                                dialogFault.dialog('close');
                                queryRecord();
                            } else if (data.code == 400) {
                                U.msg('参数验证失败');
                            } else if (data.code == 409) {
                                U.msg('已存在');
                            } else {
                                U.msg('未知异常');
                            }
                        }
                    });
                }
            }
        }, {
            text: '取消',
            handler: function () {
                dialogFault.dialog('close');
            }
        }]
    });
    old_fault_date=$("#fault_date").val();
    $("#form_fault").form("clear");

    //---------回显上一次的日期内容---------
    if (old_fault_date!=null && old_fault_date!='')
    {setVal("#fault_date",old_fault_date);}
    //------------------------

    $("#form_unit_list_temp").datagrid('loadData', { total: 0, rows: [] });
    $.getJSON(getRootPath() + "/fault/getLineList", function (json) {
        $('#form_line_id').combobox({
            data: json.rows, //获取到的json 数据
            valueField: "line_id",
            textField: "line_name"
        });
    });

    $.getJSON(getRootPath() + "/fault/getTypeDtlList", function (json) {
        console.info("数量"+json.data.length);
        $('#form_unit_temp').combobox({
            data: json.data, //获取到的json 数据
            mode:'remote',
            method:'get',
            valueField: "type_dtl_id",
            textField:'type_dtl_name',
            loader:function(param,success,error)
            {
                U.get({
                    url: getRootPath() + "/fault/getTypeDtlList",
                    loading: true,
                    data:param,
                    success: function (data) {
                        if (data.code == 200) {
                            success(data.data);
                        }else
                        {error();}
                    }
                });
            },
            formatter:function (row) {
                return `${row.type_dtl_name}-${row.type_dtl_no}-${row.sizes}`;
            }
        });
    });

    setVal("#form_maintenance_person", username);
}

function edit(id) {

    var row;
    if (id == null) {//点击datagrid上面的修改
        row = datagridFault.datagrid('getSelected');
    } else {//点击datagrid对应行上的修改
        datagridFault.datagrid('selectRow', id);
        row = datagridFault.datagrid('getSelected');
    }

    if (row == null) {
        U.msg('请先选择一项故障事件');
        return;
    }

    /*
    $.getJSON(getRootPath() + "/mtManage/assets/list_dept", function (json) {
        $('#deptInfo').combobox({
            data: json.data, //获取到的json 数据
            valueField: "dept_id",
            textField: "dept_name"
        });
        console.log(row.deptId);
        $("#deptInfo").combobox('setValue', row.deptId);
    });
    */
    $('.Unit_Add_Option').css('display','none');
    dialogFault = $("#dlg_fault").dialog({
        title: '编辑故障事件',
        width: 520,
        height: 480,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '确认',
            iconCls: 'icon-ok',
            handler: function () {
                var isValid = $("#form_fault").form('validate');
                var addObj = [{"name":"fault_id","value":row.fault_id}];
                if (isValid) {
                    U.post({
                        url: getRootPath() + "/fault/editFault",
                        loading: true,
                        data: getFormJson("#form_fault", "", addObj),
                        success: function (data) {
                            if (data.code == 200) {
                                U.msg('修改成功');
                                dialogFault.dialog('close');
                                queryRecord();
                            }else if (data.code == 400) {//参数验证失败
                                U.msg('参数验证失败');
                            }else if (data.code == 403) {
                                U.msg(data.message);
                            }else if (data.code == 404) {
                                U.msg('未找到该分类');
                            } else if (data.code == 409) {
                                U.msg('已存在');
                            } else {
                                U.msg('未知异常');
                            }
                        }
                    });
                }
            }
        }, {
            text: '取消',
            handler: function () {
                dialogFault.dialog('close');
            }
        }]
    });

    $.getJSON(getRootPath() + "/fault/getLineList", function (json) {
        $('#form_line_id').combobox({
            data: json.rows, //获取到的json 数据
            valueField: "line_id",
            textField: "line_name"
        });
        //console.log(row.line_id);
        fill_device_id=row.device_id;
        $("#form_line_id").combobox('setValue', row.line_id);
    });

    /*$.getJSON(getRootPath() + "/fault/getDeviceList?line_id="+row.line_id, function (json) {
        $('#form_device_id').combobox({
            data: json.rows, //获取到的json 数据
            valueField: "device_id",
            textField: "device_name"
        });
        $("#form_device_id").combobox('setValue', row.device_id);
        //console.log(row.device_id);
    });*/
    
    //setVal自定义函数 位置common.js 因为用了easyui-textbox 所以显示还需要特殊赋值
    $("#form_fault_type").combobox('setValue', row.fault_type);
    setVal("#form_maintenance_time", row.maintenance_time);
    setVal("#form_maintenance_person", row.maintenance_person);
    setVal("#form_fault_phenomenon", row.fault_phenomenon);
    setVal("#form_analyse", row.analyse);
    setVal("#fault_date", row.fault_date);
    setVal("#form_maintenance_measures", row.maintenance_measures);
    setVal("#form_remark", row.remark);
}

function addDtl() {
    var fault_id = $("#dlg_faultid").val();
    console.info("addDtl:"+fault_id);

    if (fault_id == null) {
        U.msg('参数错误');
        return;
    }

    dialogDtl = $("#dlg_dtl").dialog({
        title: '添加故障单元配件',
        width: 300,
        height: 200,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '确认',
            iconCls: 'icon-ok',
            handler: function () {
                var isValid = $("#form_dtl").form('validate');
                var addObj = [{"name":"fault_id","value":fault_id}];
                if (isValid) {
                    U.post({
                        url: getRootPath() + "/fault/addUnit",
                        loading: true,
                        data: getFormJson("#form_dtl", "", addObj),//$('#form_main').serialize(),
                        success: function (data) {
                            if (data.code == 200) {
                                U.msg('添加成功');
                                dialogDtl.dialog('close');
                                console.info("close:"+fault_id);
                                queryDetails();
                            } else if (data.code == 400) {
                                U.msg('参数验证失败');
                            }else if (data.code == 403) {
                                U.msg(data.message);
                            } else if (data.code == 409) {
                                U.msg('已存在');
                            } else {
                                U.msg('未知异常');
                            }
                        }
                    });
                }
            }
        }, {
            text: '取消',
            handler: function () {
                dialogDtl.dialog('close');
            }
        }]
    });
    $("#form_dtl").form("clear");
    $.getJSON(getRootPath() + "/fault/getTypeDtlList", function (json) {
        $('#type_dtl_id').combobox({
            data: json.data, //获取到的json 数据
            mode:'remote',
            method:'get',
            valueField: "type_dtl_id",
            textField:'type_dtl_name',
            loader:function(param,success,error)
            {
                U.get({
                    url: getRootPath() + "/fault/getTypeDtlList",
                    loading: true,
                    data:param,
                    success: function (data) {
                        if (data.code == 200) {
                            success(data.data);
                        }else
                        {error();}
                    }
                });
            },
            formatter:function (row) {
                return `${row.type_dtl_name}-${row.type_dtl_no}-${row.sizes}`;
            }
        });
    });
}

function editDtl(id) {
    var row;
    if (id == null) {//点击datagrid上面的修改
        row = datagridDtl.datagrid('getSelected');
    } else {//点击datagrid对应行上的修改
        datagridDtl.datagrid('selectRow', id);
        row = datagridDtl.datagrid('getSelected');
    }

    if (row == null) {
        U.msg('请先选择一项故障单元');
        return;
    }

    dialogDtl = $("#dlg_dtl").dialog({
        title: '编辑故障单元',
        width: 300,
        height: 200,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '确认',
            iconCls: 'icon-ok',
            handler: function () {
                var isValid = $("#form_dtl").form('validate');
                var addObj = [{"name":"fault_unit_id","value":row.fault_unit_id}];
                if (isValid) {
                    U.post({
                        url: getRootPath() + "/fault/editUnit",
                        loading: true,
                        data: getFormJson("#form_dtl", "", addObj),
                        success: function (data) {
                            if (data.code == 200) {
                                U.msg('修改成功');
                                dialogDtl.dialog('close');
                                queryDetails();
                            }else if (data.code == 400) {//参数验证失败
                                U.msg('参数验证失败');
                            }else if (data.code == 403) {
                                U.msg(data.message);
                            }else if (data.code == 404) {
                                U.msg('未找到该分类');
                            } else if (data.code == 409) {
                                U.msg('该分类已存在');
                            } else {
                                U.msg('未知异常');
                            }
                        }
                    });
                }
            }
        }, {
            text: '取消',
            handler: function () {
                dialogDtl.dialog('close');
            }
        }]
    });

    $.getJSON(getRootPath() + "/fault/getTypeDtlList", function (json) {
        $('#type_dtl_id').combobox({
            data: json.data, //获取到的json 数据
            mode:'remote',
            method:'get',
            valueField: "type_dtl_id",
            textField:'type_dtl_name',
            loader:function(param,success,error)
            {
                U.get({
                    url: getRootPath() + "/fault/getTypeDtlList",
                    loading: true,
                    data:param,
                    success: function (data) {
                        if (data.code == 200) {
                            success(data.data);
                        }else
                        {error();}
                    }
                });
            },
            formatter:function (row) {
                return `${row.type_dtl_name}-${row.type_dtl_no}-${row.sizes}`;
            }
        });
        $("#type_dtl_id").combobox('setValue', row.type_dtl_id);
    });

    //setVal自定义函数 位置common.js 因为用了easyui-textbox 所以显示还需要特殊赋值
    setVal("#unit_count", row.unit_count);
}

function removeDtl(id) {
    if (id == null) {
        var row = datagridDtl.datagrid('getSelected');
        if (row == null) {
            U.msg('请先选择故障单元');
            return;
        } else {
            id = row.fault_unit_id;
        }
    }

    parent.$.messager.confirm('提示', '删除后无法恢复您确定要删除？', function (data) {
        if (data) {
            U.get({
                url: getRootPath() + '/fault/deleUnit?fault_unit_id=' + id,
                loading: true,
                success: function (data) {
                    if (data.code == 200) {
                        U.msg('删除成功');
                        queryDetails();
                    } else if (data.code == 400) {//参数验证失败
                        U.msg('参数验证失败');
                    } else if (data.code == 403) {
                        U.msg(data.message);
                    }
                    else {
                        U.msg('未知异常');
                    }
                }
            });
        }
    });
}

function fault_preview(row) {
    dialogFaultPreview = $("#dlg_fault_preview").dialog({
        title: '预览设备故障',
        width: 820,
        height: 480,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '关闭',
            handler: function () {
                dialogFaultPreview.dialog('close');
            }
        }]
    });
    var fault_type_str='';
    switch (row.fault_type) {
        case 0:fault_type_str= "元器件（物料）问题";break;
        case 1:fault_type_str= "结构设计问题";break;
        case 2:fault_type_str= "软件问题";break;
        case 3:fault_type_str= "装配工艺问题";break;
        case 4:fault_type_str= "其他问题";break;
        default:fault_type_str= "未知故障类型";
    }

    //console.info(row.problem_description);
    $("#preview_fault_type").text(fault_type_str);
    $("#preview_workshop").text(row.workshop==null?"":row.workshop);
    $("#preview_maintenance_time").text(row.maintenance_time==null?"":row.maintenance_time);
    $("#preview_maintenance_person").text(row.maintenance_person==null?"":row.maintenance_person);
    $("#preview_line_name").text(row.line_name==null?"":row.line_name);
    $("#preview_device_name").text(row.device_name==null?"":row.device_name);
    $("#preview_fault_phenomenon").text(row.fault_phenomenon==null?"":row.fault_phenomenon);
    $("#preview_analyse").text(row.analyse==null?"":row.analyse);
    $("#preview_maintenance_measures").text(row.maintenance_measures==null?"":row.maintenance_measures);
    $("#preview_remark").text(row.remark==null?"":row.remark);
}

function addunit() {
    var form_unit_temp_value = $("#form_unit_temp").combobox('getValue');
    var form_unit_temp_text = $("#form_unit_temp").combobox('getText');
    var form_unit_count_temp = $("#form_unit_count_temp").val();
    if (form_unit_temp_value == null || form_unit_temp_value=='')
    {U.msg("未选择配件！");return;}
    $('#form_unit_list_temp').datagrid('appendRow',{form_unit_temp:form_unit_temp_text,value:form_unit_temp_value,form_unit_count_temp:form_unit_count_temp});

    $("#form_unit_temp").combobox('setText','');
    setVal('#form_unit_count_temp','');
}

function bindganged() {
    $("#form_line_id").combobox({
        onSelect:function (n)
        {
            console.info(n);
            $.getJSON(getRootPath() + "/fault/getDeviceList?line_id="+n.line_id, function (json) {
                $('#form_device_id').combobox({
                    data: json.rows, //获取到的json 数据
                    valueField: "device_id",
                    textField: "device_name"
                });
                if (fill_device_id!=null)
                {
                    $("#form_device_id").combobox('setValue', fill_device_id);
                    fill_device_id=null;
                }
            });
        }
    });
}

function textFormatter(value,row,index)
{
    return row.form_unit_temp+"("+row.form_unit_count_temp+"个)";
}

function ListOnDblClickRow(index, row) {
    $('#form_unit_list_temp').datagrid('deleteRow',index)
}

function exportexcel() {
    window.location.href=getRootPath() +'/fault/exportExceptionFaultData?fault_type='+$("#fault_type").combobox('getValue')+'&maintenance_person='+$("#maintenance_person").val()+
    '&device_name='+$("#device_name").val()+'&device_num='+$("#device_num").val()+'&workshop='+$("#workshop").combobox('getValue')+
    '&line_id='+$("#line_id").combobox('getValue')+'&start_fault_date='+$("#start_fault_date").val()+
        '&end_fault_date='+$("#end_fault_date").val();
}

/*
fault_type:$("#fault_type").combobox('getValue'),
    maintenance_person:$("#maintenance_person").val(),
    device_name:$("#device_name").val(),
    device_num:$("#device_num").val(),
    workshop:$("#workshop").combobox('getValue'),
    line_id:$("#line_id").combobox('getValue'),
    start_fault_date:$("#start_fault_date").val(),
    end_fault_date:$("#end_fault_date").val(),*/
